package com.gitee.qdbp.base.orm.mybatis.mapping;

import java.util.Map;
import org.apache.ibatis.builder.annotation.ProviderSqlSource;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.session.Configuration;
import com.gitee.qdbp.base.orm.mybatis.constant.Const;
import com.gitee.qdbp.base.orm.mybatis.dialect.Dialect;
import com.gitee.qdbp.base.orm.mybatis.utils.MybatisUtils;

/**
 *
 * @author gj
 * @version 150211
 */
public class CustomerProviderSqlSource implements SqlSource {

    private Configuration configuration;

    private ProviderSqlSource providerSqlSource;

    private Boolean count;

    private Dialect dialect;

    public CustomerProviderSqlSource(Configuration configuration, ProviderSqlSource providerSqlSource, Boolean count,
            Dialect dialect) {
        this.configuration = configuration;
        this.providerSqlSource = providerSqlSource;
        this.count = count;
        this.dialect = dialect;
    }

    @Override
    @SuppressWarnings("rawtypes")
    public BoundSql getBoundSql(Object parameterObject) {
        BoundSql boundSql = null;
        if (parameterObject instanceof Map && ((Map) parameterObject).containsKey(Const.PROVIDER_OBJECT)) {
            boundSql = providerSqlSource.getBoundSql(((Map) parameterObject).get(Const.PROVIDER_OBJECT));
        } else {
            boundSql = providerSqlSource.getBoundSql(parameterObject);
        }
        if (count) {
            return new BoundSql(configuration, dialect.generateCountSQL(boundSql.getSql()) /*
             * parser.getCountSql(boundSql
             * .getSql())
             */,
             boundSql.getParameterMappings(), parameterObject);
        } else {
            return new BoundSql(configuration, dialect.generatePageSQL(boundSql.getSql())/*
             * parser.getPageSql(boundSql.
             * getSql())
             */,
             MybatisUtils.plusTwoParameterToMapping(configuration, boundSql)
             //                    parser.getPageParameterMapping(configuration, boundSql)
             , parameterObject);
        }
    }

}
